using System.Collections.Generic;
using Engine;
using Engine.Graphics;
using Game;

namespace RuthlessConquest {
    public class MessagesListWidget : StackPanelWidget {
        public struct Message {
            public double CreationTime;

            public Color Color;

            public LabelWidget LabelWidget;
        }

        public List<Message> Messages = new();

        public MessagesListWidget() {
            IsHitTestVisible = false;
            Direction = LayoutDirection.Vertical;
        }

        public void AddMessage(string text, Color color, bool playSound) {
            AddMessage(
                new Message {
                    CreationTime = Time.FrameStartTime,
                    Color = color,
                    LabelWidget = new LabelWidget {
                        FontScale = 0.75f,
                        Text = text,
                        TextAnchor = TextAnchor.HorizontalCenter,
                        DropShadow = true,
                        HorizontalAlignment = WidgetAlignment.Center
                    }
                }
            );
            if (playSound) {
                AudioManager.PlaySound(Sounds.Message, true);
            }
        }

        public void ClearMessages() {
            Message[] array = Messages.ToArray();
            foreach (Message message in array) {
                RemoveMessage(message);
            }
        }

        public override void MeasureOverride(Vector2 parentAvailableSize) {
            Message[] array = Messages.ToArray();
            for (int i = 0; i < array.Length; i++) {
                Message message = array[i];
                float num = 5f;
                float num2 = num - (float)(Time.FrameStartTime - message.CreationTime);
                message.LabelWidget.Color = message.Color * MathUtils.Saturate(0.5f * num2) * MathUtils.Saturate(3f * (num - num2));
                if (num2 <= 0f) {
                    RemoveMessage(message);
                }
            }
            base.MeasureOverride(parentAvailableSize);
        }

        public void AddMessage(Message message) {
            Messages.Add(message);
            Children.Add(message.LabelWidget);
        }

        public void RemoveMessage(Message message) {
            Messages.Remove(message);
            Children.Remove(message.LabelWidget);
        }
    }
}